﻿using System;
using System.Collections.Generic;
using Fetches.Fetch.Dto;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Remote;

namespace Fetches.Fetch.Fetcher.Drivers
{
    public class WebDriverGenerator
    {
        public static readonly Dictionary<string, IWebDriver> WebDriverMap = new Dictionary<string, IWebDriver>();

        /// <summary>
        /// 获得Selenium操作对象,新版Selenium已经去掉了PhantomJs改为建议用Headless版的chrome或firefox
        /// </summary>
        /// <param name="driverName"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static IWebDriver GetWebDriver(string driverName, string key,FetchOrder order)
        {
            var seleniumGridUrl = Environment.GetEnvironmentVariable("SeleniumGridUrl");
            var remote = !string.IsNullOrEmpty(seleniumGridUrl);
            bool headless =!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("headless")) ; //是否显示浏览器窗口
            var driverPath = @"D:\App";
            if (WebDriverMap.ContainsKey(key))
            {
                return WebDriverMap[key];
            }
            IWebDriver driver = null;

            if (driverName.ToUpper() == "chrome".ToUpper())
            {
                var options = new ChromeOptions();
                if (headless)
                {
                    options.AddArguments("--headless", "--disable-gpu");
                }
                else
                {
                    options.AddArguments("--disable-plugins", "--disable-images", "--start-maximized");
                }
                driver = remote ? new RemoteWebDriver(new Uri(seleniumGridUrl),options) : new ChromeDriver(driverPath, options);
            }
            else if (driverName.ToUpper() == "firefox".ToUpper())
            {
                var options = new FirefoxOptions();
                if (headless)
                {
                    options.AddArguments("--headless", "--disable-gpu");
                }
                else
                {
                    options.AddArguments("--disable-plugins", "--disable-images", "--start-maximized");
                }
                driver = remote ? new RemoteWebDriver(new Uri(seleniumGridUrl), options) : new FirefoxDriver(driverPath, options);
            }
            WebDriverMap[key] = driver;

            return driver;
        }

    }
}
